package com.juanable.niubility.demo;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author lyg
 * @date 2022/5/12 14:21
 */
public class TestForkJoin extends RecursiveTask<Integer>{ // 带返回值
//public class TestForkJoin extends RecursiveAction { // 无返回值

    private int number = 10;

    private int start;
    private int end;

    public TestForkJoin(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if(end - start < 10) {
            //如果小于阈值，直接调用最小任务的计算方法
            return count();
        } else {
            int flag = (end + start) / 2;
            TestForkJoin left = new TestForkJoin(start, flag);
            TestForkJoin right = new TestForkJoin(flag + 1, end);
            // invokeAll()能把全部线程调度起来
            invokeAll(left, right);
            // 最后一定要记得fork()结果(如果需要结果的话)
            return left.join() + right.join();
        }
    }

    private int count() {
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum += i;
        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool joinPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
        Integer invoke = joinPool.invoke(new TestForkJoin(1, 1000000)); //同步
        ForkJoinTask<Integer> submit = joinPool.submit(new TestForkJoin(1, 1000000)); //异步
        joinPool.execute(new TestForkJoin(1, 1000000)); //异步
        System.out.println(invoke);
        System.out.println(submit.get());
    }
}
